<?php
namespace app\controller;

use app\BaseController;
use app\model\ChaozhuoAivideo;
use app\model\ChaozhuoAlarm;
use app\model\ChaozhuoEquiment;
use app\model\ChaozhuoEquimentRealtime;
use app\model\ChaozhuoFace;
use app\model\ChaozhuoFaceRecord;
use app\model\ChaozhuoTowercycle;
use app\model\ChaozhuoUploadfile;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;
use Qiniu\Auth;
use think\facade\Db;
use think\facade\Filesystem;
use think\facade\Log;
use think\Request;

// 获取所有请求头

class EqController extends BaseController
{
    public function addAiVideoUrl(Request $request)
    {
        $param = $request->all();
        $aid = $param['aid'];
        $channel = $param['channel'];
        $url = $param['url'];
        $adress = 'channel_' . $channel . '_adress';
        $switch = 'channel_' . $channel . '_switch';
        $where[] = ['id', '=', $aid];
        $ChaozhuoAivideo = ChaozhuoAivideo::where($where)->find();
        if ($ChaozhuoAivideo) {
            $ChaozhuoAivideo->$adress = $url;
            // $ChaozhuoAivideo->$switch = 1;
            $ChaozhuoAivideo->save();
        }
        return success($ChaozhuoAivideo);
    }
    public function addAiVideo(Request $request)
    {
        $param = $request->all();
        $length = $param['length'];
        // Log::write('filename: '.$param['filename'], 'addAiVideo');
        $parts = explode("/", $param['filename']);
        $eid = $parts[1]; // 第一个部分是 eid
        $filename = $parts[2]; // 第一个部分是 filename
        // 去掉文件扩展名
        $filenameWithoutExtension = pathinfo($filename, PATHINFO_FILENAME);
        // 对最后一个部分按 '_' 拆分
        $parts = explode('_', $filenameWithoutExtension);

        // if (count($parts) != 8) {
        //     return success('文件名格式不对');
        // }
        // 提取channel 和开始时间
        $channel = (int) $parts[0]; //第一部分通道号
        $start_time_parts = array_slice($parts, 1); // 从第2个部分开始是时间部分
        // 转换为标准时间格式 Y-m-d H:i:s
        $start_time = $start_time_parts[0] . '-' . $start_time_parts[1] . '-' . $start_time_parts[2] . ' ' .
            $start_time_parts[3] . ':' . $start_time_parts[4] . ':' . $start_time_parts[5];
        // 将开始时间转换为时间戳
        $start_timestamp = strtotime($start_time);
        // 计算结束时间的时间戳
        $end_timestamp = $start_timestamp + $param['length'];
        // 格式化结束时间为字符串
        $end_time = date('Y-m-d H:i:s', $end_timestamp);
        $switch = 'channel_' . $channel . '_switch';
        $adress = 'channel_' . $channel . '_adress';
        $ChaozhuoAivideo = new ChaozhuoAivideo;//添加视频记录
        $ChaozhuoAlarm = new ChaozhuoAlarm();
        if ($ChaozhuoAivideo) {
            $ChaozhuoAivideo->start_time = $start_time;
            $ChaozhuoAivideo->end_time = $end_time;
            $ChaozhuoAivideo->eid = $eid;
            $ChaozhuoAivideo->$adress = 'http://video.sdtanyue.com/' . $param['filename'];
            $ChaozhuoAivideo->$switch = 1;
            $ChaozhuoAivideo->save();
            $ChaozhuoAlarm->alarm_content = $ChaozhuoAivideo->$adress;
            $ChaozhuoAlarm->alarm_level = 1;
            $ChaozhuoAlarm->eid = $eid;
            $ChaozhuoAlarm->alarm_item = 'AI摄像头';
            $ChaozhuoAlarm->alarm_value = 0;
            // $ChaozhuoAlarm->ename = $ChaozhuoEquiment->name;
            // $ChaozhuoAlarm->pname = $ChaozhuoEquiment->pname;
            $ChaozhuoAlarm->save();
        }


        return success($ChaozhuoAivideo);
    }
    public function getQnToken(Request $request)
    {
        $accessKey = env('qn_ak');
        $secretKey = env('qn_sk');
        $bucket = env('qn_bucket');

        // 创建认证对象
        $auth = new Auth($accessKey, $secretKey);

        // 生成上传凭证
        // $token = $auth->uploadToken($bucket);
        $token = $auth->uploadToken($bucket, null, 86400);

        // 输出上传凭证，供前端使用
        return success($token);
    }

    /* 添加塔机实时数据 */
    public function createData(Request $request)
    {
        $param = $request->all(); //获取参数
        // Log::write('param: '.json_encode($param), 'createData');
        $headers = $this->request->header('dataType'); //获取设备类型
        // 键名映射
        $keyMapping = [
            "eid" => "eid",
            "height" => "tower_realtime_height",
            "amplitude" => "tower_realtime_amplitude",
            "round" => "tower_realtime_rotation",
            "angle_x" => "tower_realtime_tilt_angle",
            "wind_speed" => "tower_realtime_wind_speed",
            "weight" => "tower_realtime_weight",
            "moment" => "tower_realtime_torque", //取消力矩百分比
        ];
        $newParam = [];
        // 遍历键名映射，更新键名并过滤
        foreach ($keyMapping as $oldKey => $newKey) {
            if (isset($param[$oldKey])) {
                $newParam[$newKey] = $param[$oldKey];
            }
        }
        $where[] = ['eid', '=', $param['eid']];
        $ChaozhuoEquiment = ChaozhuoEquiment::where($where)->find();
        if (!$ChaozhuoEquiment) {
            return fail('设备不存在');
        }
        $ChaozhuoEquimentRealtime = new ChaozhuoEquimentRealtime;
        foreach ($newParam as $key => $value) {
            // $value = round($value, 2);
            $ChaozhuoEquimentRealtime->$key = $value;
            $ChaozhuoEquiment->$key = $value;
        }
        //设备online上线
        $ChaozhuoEquiment->online = 1;
        $ChaozhuoEquiment->alarm_status = 0;
        $ChaozhuoEquiment->save();
        $ChaozhuoEquimentRealtime->ename = $ChaozhuoEquiment->name;
        $ChaozhuoEquimentRealtime->pname = $ChaozhuoEquiment->pname;
        $ChaozhuoEquimentRealtime->save();

        //转发数据
        $array_001 = [15044902]; //荆州
        if (in_array($param['eid'], $array_001)) {
            $conf = [
                'host' => '122.189.98.178',
                'port' => 5672,
                'user' => 'external',
                'pwd' => '72fs32d',
                'vhost' => '/',
            ];
            $vcode = $ChaozhuoEquiment->other;
            $routingKey = 'QZSB-INTERFACE'; //路由关键字(也可以省略)
            $conn = new AMQPStreamConnection( //建立生产者与mq之间的连接
                $conf['host'], $conf['port'], $conf['user'], $conf['pwd'], $conf['vhost']
            );
            $channel = $conn->channel(); //在已连接基础上建立生产者与mq之间的通道
            $msgBody = json_encode(["data" => "00001," . $param['eid'] . "," . $param['eid'] . ",,2,15," . $param['weight'] . "," . $param['moment_percent'] . "," . $param['moment_percent'] . "," . $param['amplitude'] . "," . $param['height'] . "," . $param['round'] . "," . $param['wind_speed'] . "," . $param['angle_x'] . ",0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,,,,,,,,," . $vcode, "author" => "WT", "tag" => "DATA"]);
            Log::write($msgBody, 'forward_array_001');
            $msg = new AMQPMessage($msgBody, ['content_type' => 'text/plain', 'content-encoding' => 'utf-8', 'publisher-confirms' => true, 'publisher-returns' => true, 'template' => ['mandatory' => true]]); //生成消息
            $r = $channel->basic_publish($msg, '', $routingKey); //推送消息到某个交换机
            $channel->close();
            $conn->close();
        }

        return success();
    }

    /* 添加塔机报警数据 */
    public function createAlarmData(Request $request)
    {
        $param = $request->all(); // 获取参数
        // Log::write('param: ' . json_encode($param), 'createAlarmData');
        // 根据 alarm_type 确定 alarm_status
        $alarm_status = ($param['alarm_type'] % 2 == 0) ? 2 : 1;
        // 报警类型数组
        $alarm_array = [
            '正常', '高度上限预警', '高度上限报警', '幅度近限预警', '幅度近限报警',
            '幅度远限预警', '幅度远限报警', '重量预警', '重量报警', '力矩预警',
            '力矩报警', '风速预警', '风速报警', '防碰撞左转预警', '防碰撞左转报警',
            '防碰撞右转预警', '防碰撞右转报警', '倾角预警', '倾角报警', 'AI摄像头报警',
        ];
        // 报警类型与参数的映射
        $alarm_map = [
            1 => ['item' => '高度', 'value' => 'height'],
            2 => ['item' => '高度', 'value' => 'height'],
            3 => ['item' => '幅度', 'value' => 'amplitude'],
            4 => ['item' => '幅度', 'value' => 'amplitude'],
            5 => ['item' => '幅度', 'value' => 'amplitude'],
            6 => ['item' => '幅度', 'value' => 'amplitude'],
            7 => ['item' => '重量', 'value' => 'weight'],
            8 => ['item' => '重量', 'value' => 'weight'],
            9 => ['item' => '力矩', 'value' => 'moment'],
            10 => ['item' => '力矩', 'value' => 'moment'],
            11 => ['item' => '风速', 'value' => 'wind_speed'],
            12 => ['item' => '风速', 'value' => 'wind_speed'],
            13 => ['item' => '防碰撞', 'value' => 'round'],
            14 => ['item' => '防碰撞', 'value' => 'round'],
            15 => ['item' => '防碰撞', 'value' => 'round'],
            16 => ['item' => '防碰撞', 'value' => 'round'],
            17 => ['item' => '倾角', 'value' => 'angle_x'],
            18 => ['item' => '倾角', 'value' => 'angle_x'],
            19 => ['item' => 'AI摄像头', 'value' => 'ai_video'],
        ];
        // 获取报警项目和值
        $alarm_item = $alarm_map[$param['alarm_type']]['item'] ?? ' ';
        $alarm_value = $alarm_map[$param['alarm_type']]['value'] ?? 0;
        if ($alarm_value === 'moment') {
            $alarm_value = $param['weight'] * $param['amplitude'];
        } else {
            $alarm_value = $param[$alarm_value] ?? 0;
        }
        // 查询设备
        $ChaozhuoEquiment = ChaozhuoEquiment::where('eid', $param['eid'])->find();
        if (!$ChaozhuoEquiment) {
            return fail('设备不存在');
        }
        // 更新设备报警状态
        $ChaozhuoEquiment->alarm_status = $alarm_status;
        $ChaozhuoEquiment->alarm_status_time = date('Y-m-d H:i:s', time());
        $ChaozhuoEquiment->save();
        // 创建报警记录
        $ChaozhuoAlarm = new ChaozhuoAlarm();
        $ChaozhuoAlarm->alarm_content = $alarm_array[$param['alarm_type']] ?? '未知报警';
        $ChaozhuoAlarm->alarm_level = $alarm_status;
        $ChaozhuoAlarm->eid = $param['eid'];
        $ChaozhuoAlarm->alarm_item = $alarm_item;
        $ChaozhuoAlarm->alarm_value = $alarm_value;
        $ChaozhuoAlarm->ename = $ChaozhuoEquiment->name;
        $ChaozhuoAlarm->pname = $ChaozhuoEquiment->pname;
        $ChaozhuoAlarm->save();
        return success();
    }
    /* 添加塔机工作循环 */
    public function towerCraneWorkdata(Request $request)
    {
        $param = $request->all(); //获取参数
        // Log::write('param: '.json_encode($param), 'createData');
        $headers = $this->request->header('dataType'); //获取设备类型
        // 键名映射
        $keyMapping = [
            "eid" => "eid",
            "start_time" => "tower_start_time",
            "end_time" => "tower_end_time",
            "start_height" => "tower_start_height",
            "start_range" => "tower_start_amplitude",
            "start_rotation_angle" => "tower_start_rotation",
            "end_height" => "tower_end_height",
            "end_range" => "tower_end_amplitude",
            "end_rotation_angle" => "tower_end_rotation",
            "end_weight" => "tower_end_load",
            "start_weight" => "tower_start_load",
        ];
        $newParam = [];
        // 遍历键名映射，更新键名并过滤
        foreach ($keyMapping as $oldKey => $newKey) {
            if (isset($param[$oldKey])) {
                $newParam[$newKey] = $param[$oldKey];
            }
        }
        $where[] = ['eid', '=', $param['eid']];
        $ChaozhuoTowercycle = new ChaozhuoTowercycle;
        foreach ($newParam as $key => $value) {
            // $value = round($value, 2);
            $ChaozhuoTowercycle->$key = $value;
        }
        $ChaozhuoTowercycle->save();
        return success();
    }
    /* 安卓远程软件下载地址 */
    public function getRangeUrl(Request $request)
    {
        $id = $request->param('id');
        $url = 'https://dl-customise.sunlogin.oray.com/sunlogin/customise/slrca/d/ddabedde6571ce29e797b987f9f41255/TenYirRemote.apk';
        if ($id == 1) {
            $url = 'https://dl-customise.oray.com/sunlogin/customise/slrca/1/1fa6b52bf4551fadc69298f63c3debeb/RemoteControl.apk'; //探越
        }
        return success($url);
    }
    public function getSoftwareUrl(Request $request)
    {
        $where = [];
        if ($request->has('type')) {
            $type = $request->param('type');
            $where[] = ['type', '=', $type];
        }
        $softwareurl = DB::table('softwareurl')->where($where)->find();
        return success($softwareurl);
    }
    /* 设备校验 */
    public function verificationEquipment(Request $request)
    {
        $param = $request->all(); //获取参数
        $ChaozhuoEquiment = ChaozhuoEquiment::where('mac', $param['mac'])->find();
        if (!empty($ChaozhuoEquiment)) {
            foreach ($request as $key => $value) {
                $ChaozhuoEquiment->$key = $value;
            }
            $ChaozhuoEquiment->save();
        } else {
            return fail(null, 'mac不存在', -1);
        }
        return success($ChaozhuoEquiment);
    }
    /* 获取人脸信息 */
    public function getStaffInfo(Request $request)
    {
        $where = [];
        if ($request->has('eid')) {
            $eid = $request->param('eid');
            $where[] = ['eid', '=', $eid];
        } else {
            return fail(null, '缺少必要参数');
        }
        if (!$request->param('page')) {
            $face_url = ChaozhuoFace::where($where)->field('id,name,url,phone,eid')->select();
            return success($face_url);
        }
        // return success($deviceId);
        $face_url = ChaozhuoFace::where($where)->field('id,name,url,phone,eid')->paginate(['list_rows' => $request->param('pageSize', 10), 'page' => $request->param('current', 1)]);
        return pageReturn($face_url);
    }
    /* 添加考勤信息 */
    public function addAttendance(Request $request)
    {
        $request = $request->all(); //获取参数
        $ChaozhuoFaceRecord = new ChaozhuoFaceRecord;
        foreach ($request as $key => $value) {
            $ChaozhuoFaceRecord->$key = $value;
        }
        $rq = $ChaozhuoFaceRecord->save();
        return success($rq);
    }
    public function uploadFaceImg(Request $request)
    {
        $upload_url = env('UPLOAD_URL', true);
        $post = $request->post();
        $file = request()->file('file');
        //$文件名
        $fileName = $file->getOriginalName();
        $date = date('Y_m_d', time()); //当天日期
        $fileOssName = time() . $fileName; //阿里云文件名
        $ext = $file->getOriginalExtension(); //文件扩展名
        $ext = 'face';
        // $ossurl = config('filesystem.disks.aliyun.url');
        // 上传本地服务器
        $res = Filesystem::disk('public')->putFileAs($ext . '/' . $date, $file, $fileOssName); //按照文件类型分类
        $res = stripslashes($res); //去除转义字符
        $fileurl = 'https://' . $upload_url . '/' . $res;
        //地址存入数据库
        $upload = new ChaozhuoUploadfile;
        $upload->url = $fileurl;
        $upload->filename = $fileOssName;
        $upload->save();

        return success($fileurl);
    }
    public function uploadFace()
    {
        $request = $this->request->param();
        if (isset($request['id'])) {
            $ChaozhuoFace = ChaozhuoFace::find($request['id']);
        } else {
            $ChaozhuoFace = new ChaozhuoFace;
        }
        foreach ($request as $key => $value) {
            $ChaozhuoFace->$key = $value;
        }
        $ChaozhuoFace->update = time();
        $rq = $ChaozhuoFace->save();
        return success($rq);
    }
    public function gb28181Config()
    {
        $param = $this->request->param(); //获取参数
        $where[] = ['eid', '=', $param['eid']];
        $ChaozhuoEquiment = ChaozhuoEquiment::where($where)->find();
        if (!$ChaozhuoEquiment) {
            return fail('设备不存在');
        }
        foreach ($param as $key => $value) {
            $ChaozhuoEquiment->$key = $value;
        }
        $ChaozhuoEquiment->save();
        return success($ChaozhuoEquiment);
    }
}
//自定义Class项目
class My
{
    /* 添加塔机报警数据 */
    public function createAlarmData_old(Request $request)
    {
        $param = $request->all(); //获取参数

        // 根据 alarm_type 确定 alarm_status
        // 如果 alarm_type 是偶数，则为报警（2），如果是奇数，则为预警（1）
        $alarm_status = ($param['alarm_type'] % 2 == 0) ? 2 : 1;

        $alarm_array = ['正常', '高度上限预警', '高度上限报警', '幅度近限预警', '幅度近限报警', '幅度远限预警', '幅度远限报警', '重量预警', '重量报警', '力矩预警', '力矩报警', '风速预警', '风速报警', '防碰撞左转预警', '防碰撞左转报警', '防碰撞右转预警', '防碰撞右转报警', '倾角预警', '倾角报警'];

        switch ($param['alarm_type']) {
            case 1:
            case 2:
                $alarm_item = '高度';
                $alarm_value = $param['height'];
                break;
            case 3:
            case 4:
            case 5:
            case 6:
                $alarm_item = '幅度';
                $alarm_value = $param['amplitude'];
                break;
            case 7:
            case 8:
                $alarm_item = '重量';
                $alarm_value = $param['weight'];
                break;
            case 9:
            case 10:
                $alarm_item = '力矩';
                $alarm_value = $param['weight'] * $param['amplitude'];
                break;
            case 11:
            case 12:
                $alarm_item = '风速';
                $alarm_value = $param['wind_speed'];
                break;
            case 13:
            case 14:
            case 15:
            case 16:
                $alarm_item = '防碰撞';
                $alarm_value = $param['round'];
                break;
            case 17:
            case 18:
                $alarm_item = '倾角';
                $alarm_value = $param['angle_x'];
                break;
            default:
                $alarm_item = ' ';
                $alarm_value = 0;
                break;
        }
        $where[] = ['eid', '=', $param['eid']];
        $ChaozhuoEquiment = ChaozhuoEquiment::where($where)->find();
        if (!$ChaozhuoEquiment) {
            return fail('设备不存在');
        }
        $ChaozhuoEquiment->alarm_status = $alarm_status;
        $ChaozhuoEquiment->alarm_status_time = date('Y-m-d H:i:s', time());
        $ChaozhuoEquiment->save();
        // die;
        $ChaozhuoAlarm = new ChaozhuoAlarm;
        $ChaozhuoAlarm->alarm_content = $alarm_array[$param['alarm_type']];
        $ChaozhuoAlarm->alarm_level = $alarm_status;
        $ChaozhuoAlarm->eid = $param['eid'];
        $ChaozhuoAlarm->alarm_item = $alarm_item;
        $ChaozhuoAlarm->alarm_value = $alarm_value;

        $ChaozhuoAlarm->save();
        return success();
    }
}
